#encoding:utf-8 

import os, sys, string, shutil, json
import logging 


# linux windows文件路径兼容
def path_compatible(path):
    return string.replace(path, "/", os.sep)


#拷贝文件夹下内容
def copy_(frompath_, tarpath_, ignorefile=""):
    for item in os.listdir(frompath_):
        itemobj = os.path.join(frompath_, item)
        if os.path.isfile(itemobj):
            if item != ignorefile:
                shutil.copy(itemobj, tarpath_)
            else:
                logging.info("Copy ignore the file -->> %s!"%ignorefile)
            
        elif os.path.isdir(itemobj):
            tardir = os.path.join(tarpath_, item)
            if not os.path.isdir(tardir):
                os.mkdir(tardir)
            copy_(itemobj, tardir)


#add tools lib
# import init
# from remote import RemoteCtrl

'''热更资源管理工具'''
class ResVer:

    NET_INFO = dict(
            local = ["10.7.1.215", "root", "kaixIN))!"],
            remote = []
        )

    PLAT_RESDIR = dict(
        win32 = "res",
        android = "res_etc1",
        ios = "res_pvr"
    )

    CFG_JSON = "resver.json"

    # 根据版本号  打出最新热更资源 
    @classmethod
    def newver(cls, binpath, bigV, smallV, platform, beginSvnCode, endSvnCode, desc):
        basedir = os.getcwd()
        

        #read json-file 
        filejson = os.path.join(basedir, cls.CFG_JSON)
        filecont = file(filejson, 'r+')
        cfg = json.loads(filecont.read().decode("utf-8"))
        filecont.close() 

        #chk config
        if cfg.has_key(bigV) == False:
            logging.error("Not have the bin ver")
            return 
        if cfg[bigV].has_key(smallV) == False:
            logging.error("Not have the res ver")
            return 

        cfgres = cfg[bigV][smallV]
        svns = cfgres[0]
        svne = cfgres[1]
        svndesc = cfgres[2]

        #rea path 
        winpath = path_compatible(basedir + "/../%s"%cls.PLAT_RESDIR["win32"])
        svnpath = path_compatible(basedir + "/../%s"%cls.PLAT_RESDIR[platform])
        #template verres path 
        tmppath = path_compatible(basedir + "/TEMPLATE_RES")
        tmpres = os.path.join(tmppath, "res")

        #execute
        #因为每次认定脚本都更新 直接打出来lpkg到指定资源路径
        [gamefile,  configfile] = init.LuaGame.lua_lpack(os.path.realpath(winpath), binpath, True)
        if (platform != "win32"):
            gametarfile = os.path.join(svnpath, gamefile.split(os.sep)[-1])
            configtarfile = os.path.join(svnpath, configfile.split(os.sep)[-1])
            if os.path.isfile(gametarfile):
                os.remove(gametarfile)
            if os.path.isfile(configtarfile):
                os.remove(configtarfile)

            shutil.move(gamefile, svnpath)
            shutil.move(configfile, svnpath)
            os.remove(gametarfile)
            os.remove(configtarfile)
        print ("Copy file {fromfile} to target path {targetpath}".format(fromfile=gamefile, targetpath=svnpath))
        init.LuaGame.svn_difflist(svnpath, svns, svne, tmpres)
        init.LuaGame.crt_verinfo_list(tmpres, os.path.join(tmppath, "%s_%s.data"%(bigV, smallV)), type="json")
        retdir = path_compatible(basedir + "/resver_TEMPLATE/%s/%s")%(bigV, smallV)
        if os.path.isdir(retdir):
            shutil.rmtree(retdir)
        os.renames(tmppath, retdir)

        #zip the res path
        zipbin = path_compatible(binpath + "/bin/zip.exe") if sys.platform == "win32" else "zip "
        zipname = "%s_%s.zip"%(bigV, smallV)
        cmd_zip = "cd {resdir} && {zipbin} -q -r {zipname} {tmppath}".format(resdir=path_compatible("./resver_TEMPLATE"), zipbin=zipbin, \
                                                                        zipname=zipname, \
                                                                        tmppath=path_compatible("./%s"%bigV)) 
        os.system(cmd_zip)

        retdir2 = path_compatible(basedir + "/resver/%s/%s")%(bigV, smallV)
        copy_(path_compatible(basedir + "/resver_TEMPLATE"), path_compatible(basedir + "/resver"))
        shutil.rmtree(path_compatible(basedir + "/resver_TEMPLATE"))

    # 上传部署zip包
    @classmethod
    def upload(cls, respack, placename="local"):
        #内网
        NET_INFO = cls.NET_INFO
        cfg = NET_INFO[placename]
        cli = RemoteCtrl(cfg[0], cfg[1], cfg[2])
        zipname = string.split(respack, os.sep)[-1]
        tarpath = "/data0/svr_redwar/svr/static"
        tarfile = "/data0/svr_redwar/svr/static/%s"%zipname
        logging.info("Upload the file %s to the %s %s"%(respack, cfg[0], tarfile))
        cli.ssh_command("rm -f {tarfile}".format(tarfile=tarfile))
        
        cli.commit_file(respack, tarfile)
        logging.info("unzip the file....")
        cli.ssh_command("cd {tarpath} && unzip -o {zipname}".format(tarpath=tarpath, zipname=zipname))
        cli.close()


    # 删除静态资源包
    @classmethod
    def remotedel(cls, binpack, respack=None, placename="local"):
        #内网
        NET_INFO = cls.NET_INFO
        cfg = NET_INFO[placename]

        keyfile = os.path.join(os.getcwd() , "wenbin")
        cli = RemoteCtrl(cfg[0], loginname = cfg[1], pwd = cfg[2])
        if respack == None:
            cli.ssh_command("rm -rf {binpath}".format(binpath="/data0/svr_redwar/svr/static/%s"%binpack))
        else:
            cli.ssh_command("rm -f {zipfile}".format(zipfile="/data0/svr_redwar/svr/static/%s_%s.zip"%(binpack,respack)))
            cli.ssh_command("rm -rf {binpath}".format(binpath="/data0/svr_redwar/svr/static/%s/%s"%(binpack,respack)))
        cli.close()

if __name__ == "__main__":
    ResVer.remotedel("1.3.0", "1001")
    ResVer.newver("1.3.0", "1001")
    ResVer.upload(path_compatible(os.getcwd() + "/resver/1.3.0_1001.zip"))
    print("Done!")